package com.sk.cardeal.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.cardeal.app.MyApplication;
import com.sk.cardeal.entity.JiaShiEntity;
import com.sk.cardeal.entity.UserBean;
import com.sk.cardeal.entity.XingShiEntity;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by sk on 2017/12/7.
 */

public class MyUtils {

    public static LoadingDialog getLoadingDialog(Context context, boolean isCancel) {
        MyDialogLoadingFactory myLoadingFactory = new MyDialogLoadingFactory();
        LoadingDialog loadingDialog = LoadingDialog.make(context, myLoadingFactory);
        loadingDialog.setCancelable(isCancel);
        return loadingDialog;
    }

    public static String getRndNumCode() {
        Random rand = new Random();
        long t = System.currentTimeMillis();
        return t * 1000L + (long) rand.nextInt(1000) + "";
    }


    public static boolean isFormat(Context context, List<EditText> editTexts) {
        for (EditText editText : editTexts) {
            if (TextUtils.isEmpty(editText.getText().toString())) {
                String tip = (String) editText.getTag();
                Toast.makeText(context, tip, Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    /*
   * 将时间戳转换为时间
   */
    public static String stampToDate(long s) {
        String res = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date(s);
        res = simpleDateFormat.format(date);
        return res;
    }

    public static XingShiEntity jsonToXingshi(String result) {

        XingShiEntity xingShiEntity = new XingShiEntity();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
        String dataObj = jsonObject.getString("words_result");
        Map<String, Map<String, String>> params = JSON.parseObject(dataObj, new TypeReference<Map<String, Map<String, String>>>() {
        });
//        Log.v("jsonToXingshi",JSON.toJSONString(params));
        xingShiEntity.setAddress(params.get("住址").get("words"));
        xingShiEntity.setCarGetCode(params.get("车辆识别代号").get("words"));
        xingShiEntity.setCarModel(params.get("品牌型号").get("words"));
        xingShiEntity.setCarNumber(params.get("号牌号码").get("words"));
        xingShiEntity.setEngineNumber(params.get("发动机号码").get("words"));
        xingShiEntity.setGetDate(params.get("发证日期").get("words"));
        xingShiEntity.setRegisterDate(params.get("注册日期").get("words"));
        xingShiEntity.setOwner(params.get("所有人").get("words"));
        xingShiEntity.setUseType(params.get("使用性质").get("words"));
        xingShiEntity.setCarType(params.get("车辆类型").get("words"));
        return xingShiEntity;
    }

    public static JiaShiEntity jsonToJiashi(String result) {

        try {
            JiaShiEntity jiaShiEntity = new JiaShiEntity();
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
            String dataObj = jsonObject.getString("words_result");
            Map<String, Map<String, String>> params = JSON.parseObject(dataObj, new TypeReference<Map<String, Map<String, String>>>() {
            });
//        Log.v("jsonToXingshi",JSON.toJSONString(params));
            jiaShiEntity.setAddress(params.get("住址").get("words"));
            jiaShiEntity.setBirthDay(params.get("出生日期").get("words"));
            jiaShiEntity.setCardNum(params.get("证号").get("words"));
            jiaShiEntity.setCountry(params.get("国籍").get("words"));
            jiaShiEntity.setDriveCarType(params.get("准驾车型").get("words"));
            jiaShiEntity.setName(params.get("姓名").get("words"));
            jiaShiEntity.setOnceGetDate(params.get("初次领证日期").get("words"));
            jiaShiEntity.setSex(params.get("性别").get("words"));
            if (params.containsKey("有效起始日期")) {
                jiaShiEntity.setStartTime(params.get("有效起始日期").get("words"));
                jiaShiEntity.setTerm(params.get("有效期限").get("words"));

            } else {
                jiaShiEntity.setStartTime(params.get("有效期限").get("words"));
                jiaShiEntity.setToTime(params.get("至").get("words"));
                int start = Integer.parseInt(params.get("有效期限").get("words").substring(0, 4));
                int end = Integer.parseInt(params.get("至").get("words").substring(0, 4));
                Log.v("JiaShiEntity",start+"");
                Log.v("JiaShiEntity",end+"");
                jiaShiEntity.setTerm(String.valueOf(end - start) + "年");
            }
            return jiaShiEntity;
        } catch (Exception e) {
            Toast.makeText(MyApplication.getAppContext(), "解析有误，请重试！", Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    public static String getDate(String s) {
        try {
            String year = s.substring(0, 4);
            String month = s.substring(4, 6);
            String day = s.substring(6, 8);
            return year + "-" + month + "-" + day;
        }catch (Exception e){
            return "2018-01-01";
        }
    }

    public static boolean isCarNumber(String s) {
        Pattern pattern = Pattern.compile("^[\u4e00-\u9fa5|WJ]{1}[A-Z0-9]{6}$");
        Matcher matcher = pattern.matcher(s);
        if (!matcher.matches()) {
            System.out.println("车牌号格式不对！");
            return false;
        } else {
            System.out.println("车牌号格式正确！");
            return true;
        }
    }

    public static UserBean.ReturnObjectBean getUser(Context context) {
        String result = (String) SPUtils.get(MyApplicationLike.getAppContext(), "userInfo", "");
        if (result != null && result.length() > 0) {
            UserBean userBean = JSON.parseObject(result, UserBean.class);
            return userBean.getReturnObject();
        } else {
            return null;
        }
    }


    /**
     * 提供精确的加法运算。
     *
     * @param v1 被加数
     * @param v2 加数
     * @return 两个参数的和
     */
    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }

    /**
     * 提供精确的减法运算。
     *
     * @param v1 被减数
     * @param v2 减数
     * @return 两个参数的差
     */
    public static double sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 提供精确的乘法运算。
     *
     * @param v1 被乘数
     * @param v2 乘数
     * @return 两个参数的积
     */
    public static double mul(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).doubleValue();
    }

    /**
     * 提供（相对）精确的除法运算，当发生除不尽的情况时，精确到
     * 小数点以后10位，以后的数字四舍五入。
     *
     * @param v
     * @param v1 被除数
     * @param v2 除数
     * @return 两个参数的商
     */
    public static double div(double v, double v1, double v2) {
        return div(v1, v2, DEF_DIV_SCALE);
    }

    //默认除法运算精度
    private static final int DEF_DIV_SCALE = 10;

    public static void setTranslucent(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 设置状态栏透明
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    /**
     * get App versionCode
     *
     * @param context
     * @return
     */
    public static String getVersionCode(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        String versionCode = "";
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionCode = packageInfo.versionCode + "";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * get App versionCode
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        String versionName = "";
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName + "";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }
}
